package com.boot.dog.web.security.handler;

import com.boot.dog.web.security.util.SecurityResult;
import com.boot.dog.web.security.exception.ValidateCodeException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: MaxLv
 * @Date: 2019/12/2
 */
@Component
public class AuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) {
        if (exception instanceof ValidateCodeException) {
            SecurityResult.fail(response, exception.getMessage());
        }
        if (exception instanceof UsernameNotFoundException) {
            SecurityResult.fail(response, exception.getMessage());
        }
        if (exception instanceof BadCredentialsException) {
            SecurityResult.fail(response, "用户认证错误,请联系管理员");
        }
        if (exception instanceof LockedException) {
            SecurityResult.fail(response, "账户已被禁用,请联系管理员");
        }
        SecurityResult.fail(response, "用户名或密码错误");
    }
}
